package com.hy.demo.learn.thread.生产电脑;

/**
 * <p>
 *  多线程 生产者消费者实例demo
 * </p>
 *
 * @author cjl
 * @version 1.0
 * @since 2020-08-27 10:36
 */

class Computer {

    private static int count = 0;
    private String     name;
    private Double     price;

    public Computer(String name, Double price) {
        this.name = name;
        this.price = price;
        count++;
    }

    @Override
    public String toString() {

        return "第" + count + "台电脑】" + "电脑名字" + name + ",价格" + price;
    }
}

class Resource {
    private Computer computer;

    public synchronized void make() throws Exception {
        if (this.computer != null) {
            super.wait();
        }
        Thread.sleep(100);
        this.computer = new Computer("Dell牌电脑", 1.1);

        System.out.println("生产电脑" + this.computer);
        super.notifyAll();
    }

    public synchronized void get() throws Exception {
        if (this.computer == null) {
            super.wait();
        }
        Thread.sleep(10);
        System.out.println("取走电脑" + this.computer);
        this.computer = null;
        super.notifyAll();
    }
}

class Producer implements Runnable {

    private Resource resource;

    public Producer(Resource resource) {
        this.resource = resource;
    }

    @Override
    public void run() {

        for (int i = 0; i < 50; i++) {
            try {
                this.resource.make();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

class Consumer implements Runnable {

    private Resource resource;

    public Consumer(Resource resource) {
        this.resource = resource;
    }

    @Override
    public void run() {

        for (int i = 0; i < 50; i++) {
            try {
                this.resource.get();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

public class ThreadDemo {

    public static void main(String[] args) {
        Resource resource = new Resource();

        new Thread(new Producer(resource), "厂家生产--A").start();
        new Thread(new Consumer(resource), "客户取走--X").start();
    }
}
